package com.soilflow.info.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.soilflow.common.annotation.DataScope;
import com.soilflow.common.constant.MqConstants;
import com.soilflow.common.domain.LandAuction2;
import com.soilflow.common.domain.dto.LandAuctionDto;
import com.soilflow.common.domain.vo.LandAuctionVo;
import com.soilflow.common.mybatisplus.BaseEntity;
import com.soilflow.common.utils.NoUtils;
import com.soilflow.common.utils.SecurityUtils;
import com.soilflow.common.utils.StringUtils;
import com.soilflow.info.mapper.LandInfoMapper;
import com.soilflow.system.mapper.SysDictDataMapper;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.soilflow.info.mapper.LandAuctionMapper;
import com.soilflow.common.domain.LandAuction;
import com.soilflow.info.service.LandAuctionService;
import org.springframework.util.ObjectUtils;

/**
@author dhp 
@date 2023/4/24 - 16:42
*/
@Service
public class LandAuctionServiceImpl extends ServiceImpl<LandAuctionMapper, LandAuction> implements LandAuctionService{

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Resource
    private LandAuctionMapper landAuctionMapper;

    @Resource
    private LandInfoMapper landInfoMapper;



    @Override
    public List<LandAuctionVo> getLandAuctionInfo(LandAuctionDto dto) {
        //查询竞拍基本信息
        List<LandAuctionVo> vos = landAuctionMapper.getLandAuctionInfo(dto);
        return vos;
    }

    @Override
    public Boolean saveLandAuctionInfo(LandAuctionDto dto) {
            //1 校验竞拍信息和土地信息
            LambdaQueryWrapper<LandAuction> auctionQuery = new LambdaQueryWrapper<>();
            auctionQuery.eq(StringUtils.isNotEmpty(dto.getAuctionName()),LandAuction::getAuctionName,dto.getAuctionName())
                    .last("limit 1");
            if (ObjectUtils.isEmpty(landAuctionMapper.selectOne(auctionQuery))){
                //2 添加竞拍信息
                try {
                    LandAuction data = new LandAuction();
                    BeanUtils.copyProperties(dto, data);
                    String landAuctionCode = NoUtils.getLandAuctionCode(SecurityUtils.getUserId());
                    data.setCode(landAuctionCode);
                    landAuctionMapper.insert(data);
                    return true;
                }finally {
                    Map dataMap = new HashMap();
                    String message = null;
                    //发送延迟修改状态信息
                    Long id = landAuctionMapper.selectOne(auctionQuery).getId();
                    dataMap.put("id",id);
                    //报名中
                    dataMap.put("type","applyStartDelayTime");
                    message = JSON.toJSONString(dataMap);
                    rabbitTemplate.convertAndSend(MqConstants.DELAYED_EXCHANGE_NAME, MqConstants.AUCTION_PUBLISH_KEY,message, messagePostProcessor -> {
                        messagePostProcessor.getMessageProperties().setDelay(dto.getApplyStartDelayTime());
                        return messagePostProcessor;
                    });
                    //即将开始
                    dataMap.remove("type");
                    dataMap.put("type","applyEndDelayTime");
                    message = JSON.toJSONString(dataMap);
                    rabbitTemplate.convertAndSend(MqConstants.DELAYED_EXCHANGE_NAME, MqConstants.AUCTION_PUBLISH_KEY,message, messagePostProcessor -> {
                        messagePostProcessor.getMessageProperties().setDelay(dto.getApplyEndDelayTime());
                        return messagePostProcessor;
                    });
                    //竞拍中
                    dataMap.remove("type");
                    dataMap.put("type","auctionStartDelayTime");
                    message = JSON.toJSONString(dataMap);
                    rabbitTemplate.convertAndSend(MqConstants.DELAYED_EXCHANGE_NAME, MqConstants.AUCTION_PUBLISH_KEY,message, messagePostProcessor -> {
                        messagePostProcessor.getMessageProperties().setDelay(dto.getAuctionStartDelayTime());
                        return messagePostProcessor;
                    });
                    //竞拍完成
                    dataMap.remove("type");
                    dataMap.put("type","auctionEndDelayTime");
                    message = JSON.toJSONString(dataMap);
                    rabbitTemplate.convertAndSend(MqConstants.DELAYED_EXCHANGE_NAME, MqConstants.AUCTION_PUBLISH_KEY,message, messagePostProcessor -> {
                        messagePostProcessor.getMessageProperties().setDelay(dto.getAuctionEndDelayTime());
                        return messagePostProcessor;
                    });

                }
            }
            return false;
        }


    @Override
    public LandAuctionVo getAuctionInfoById(Long id) {
        return landAuctionMapper.getAuctionInfoById(id);
    }

    @Override
    public void updateAuctionInfo(LandAuctionDto dto) {
        LandAuction landAuction = new LandAuction();
        BeanUtils.copyProperties(dto,landAuction);
        landAuction.setId(dto.getId());
        landAuctionMapper.updateById(landAuction);
    }

    @DataScope(deptAlias = "li")
    @Override
    public  List<String> getLandInfoByName(LandAuctionDto dto) {
        return landAuctionMapper.getLandInfoByName(dto);
    }

    @DataScope(deptAlias = "li")
    @Override
    public  List<LandAuctionVo> getLandNameFormLandInfo(LandAuctionDto dto) {
       return landAuctionMapper.getLandNameFormLandInfo(dto);
    }


    //修改竞拍状态
    @RabbitListener(queues = MqConstants.AUCTION_PUBLISH_QUEUE)
    @Override
    public void modifyAuctionStatus(String message) throws ParseException {
        Map map = JSON.parseObject(message, Map.class);
        Long id = Long.valueOf(map.get("id").toString());
        String type = map.get("type").toString();
        LambdaUpdateWrapper<LandAuction> updateQuery = new LambdaUpdateWrapper<>();
        if ("applyStartDelayTime".equals(type)){
            updateQuery.eq(BaseEntity::getId,id).set(LandAuction::getStatus ,1);
            landAuctionMapper.update(null,updateQuery);
        }else if ("applyEndDelayTime".equals(type)){
            updateQuery.eq(BaseEntity::getId,id).set(LandAuction::getStatus ,2);
            landAuctionMapper.update(null,updateQuery);
        }else if ("auctionStartDelayTime".equals(type)){
            updateQuery.eq(BaseEntity::getId,id).set(LandAuction::getStatus ,3);
            landAuctionMapper.update(null,updateQuery);
        }else if ("auctionEndDelayTime".equals(type)){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            LandAuction landAuction = landAuctionMapper.selectById(id);
            Long endTime = sdf.parse(landAuction.getAuctionEnd()).getTime();
            if (System.currentTimeMillis() >= endTime){
                updateQuery.eq(BaseEntity::getId,id).set(LandAuction::getStatus ,4);
                landAuctionMapper.update(null,updateQuery);
            }
        }


    }

    @Override
    public LandAuctionVo getAuctionInfoByInfoId(Long infoId) {
        return       landAuctionMapper.getAuctionInfoByInfoId(infoId);

    }

    @Override
    public void updateStatus(LandAuction2 landAuction) {
        landAuctionMapper.updateStatus(landAuction);
    }
}
